import {
  login,
  logout,
  getUserInfo
} from '@/api/user'
import {
  resetRouter
} from '@/router'


const getDefaultState = () => {
  return {
    token: null,
    userName: '',
    shouldRefreshToken: true
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKENS: (state, token) => {
    state.token = token;
    localStorage.setItem('token', token);
  },
  SET_NAME: (state, name) => {
    state.userName = name
    localStorage.setItem('userName', name);
  },
  CLEAR_TOKENS(state) {
    state.token = null;
  },
  LOGOUT(state) {
    state.token = null;
    state.user = null;
    state.shouldRefreshToken = false; // 禁用自动刷新
  },
  ENABLE_REFRESH(state) {
    state.shouldRefreshToken = true; // 启用自动刷新
  },
}


const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      userName,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        userName: userName.trim(),
        password: password
      }).then(response => {
        // console.log(response, 'response')
        const {
          data
        } = response;
        commit('SET_TOKENS', response.token)
        // setToken(response.token)
        commit('SET_NAME', data.userName)
        // 启用自动刷新token
        commit('ENABLE_REFRESH')
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getUserInfo({
          'Authorization': localStorage.getItem('token'), // 使用 header 方式传递 token
          'Content-Type': 'application/json'
      }).then(response => {
        // console.log(response)
        if (response.code === 401) {
          return reject('登录状态已过期，请重新登录')
        }
        const data = response[0]
        const {
          userName
        } = data
        // commit('SET_TOKENS', response.token)
        commit('SET_NAME', userName)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  //刷新token
  async refreshTokens({
    commit
  }) {
    try {
      const refreshToken = localStorage.getItem('token');
      const {
        data
      } = await refreshToken(refreshToken);
      commit('SET_TOKENS', data);
    } catch (error) {
      console.error(error);
    }
  },

  // user logout
  logout({
    commit,
    state
  }) {
    commit('CLEAR_TOKENS'); // must remove  token  first
    resetRouter()
    commit('RESET_STATE')
    localStorage.removeItem('token');
    // 禁用自动刷新
    commit('LOGOUT')
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then((res) => {
    //     commit('CLEAR_TOKENS'); // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('CLEAR_TOKENS'); // must remove  token  first
      localStorage.removeItem('token');
      commit('RESET_STATE')
      resolve()
    })
  }
}



export default {
  namespaced: true,
  state,
  mutations,
  actions
}
